Repository navigation
Conversation
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR introduces validation enhancements (stripUnknown option in Joi, stricter load schema), adds a new POST /refresh endpoint to auth routes, removes email service verification step, makes the ApiResponse type generic, refactors service imports, and adds comprehensive unit and integration test coverage for auth and load functionality. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (2 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 10
🤖 Fix all issues with AI agents
In `@src/middlewares/joiValidation.ts`:
- Line 10: The middleware default options set stripUnknown: true which removes
unknown properties before Joi runs, so schemas that use .unknown(false) (e.g.
loadSchema used via validateSchema(loadSchema) in src/routes/load.ts) never get
an "unknown field" error; fix by either removing stripUnknown: true from the
default Joi.ValidationOptions in the middleware (options variable in
joiValidation.ts) or make validateSchema accept/forward custom options and
update the call site validateSchema(loadSchema) to pass { stripUnknown: false }
for strict schemas like loadSchema so Joi's .unknown(false) can reject extra
keys.
In `@src/routes/auth.ts`:
- Line 21: The /refresh route currently lacks the authlimiter middleware and the
refresh controller (function refresh in src/controllers/auth.ts) dereferences
req.signedCookies["tokens"].refreshToken without checking for tokens, which can
throw a TypeError and allows brute forcing; update the router.post("/refresh",
refresh) registration to include the existing authlimiter middleware (same as
used for /login and /register) and add a guard at the start of the refresh
controller to validate presence of req.signedCookies["tokens"] and
tokens.refreshToken, returning a 401 JSON API response (using createAPIResponse)
if missing; ensure the change references the refresh handler and authlimiter
symbol so the middleware and null-check are applied consistently.
In `@src/types/index.ts`:
- Around line 23-30: The ApiResponseinput<T> generic isn’t propagated because
createAPIResponse is not generic; update the createAPIResponse function to
accept a generic type parameter (e.g., function createAPIResponse<T>(input:
ApiResponseinput<T>)) and have it return the appropriately typed response
including the added timestamp so callers receive the correct generic typing for
data/datas; reference the ApiResponseinput and createAPIResponse symbols when
making this change.
In `@src/validations/load.ts`:
- Line 15: The unknown(false) check in loadSchema is ineffective because the
middleware in joiValidation.ts currently strips unknown properties by default;
update the call site that applies validateSchema(loadSchema) to pass an override
option { stripUnknown: false } (or alternatively remove/disable stripUnknown in
joiValidation.ts) so that unknown(false) can actually reject unknown fields;
reference the loadSchema defined in src/validations/load.ts and the
validateSchema(...) usage in your route/middleware to apply the fix.
In `@tests/auth/auth.test.ts`:
- Around line 69-85: Fix the minor formatting in the test hooks by adding a
space after the comma in the timeout parameter for both beforeAll and afterAll;
locate the beforeAll(...) and afterAll(...) invocations (which call connectDB(),
use mongoose.connection.db to deleteMany on the "users" collection with
testEmail, and call mongoose.disconnect()) and change the timeout argument
formatting from "},20000);" to "}, 20000);" in both places.
- Around line 87-115: The tests are dependent on shared state; make them
independent by either (A) moving the shared setup into a beforeAll that calls
registerUser() (and verifyUser() if needed) and then querying Users.findOne({
email: testEmail }) in tests, or (B, preferred) have each it() create its own
user by calling registerUser() with a unique email and, when needed, calling
verifyUser() or loginUser() within the same test so registerUser, verifyUser,
and loginUser are invoked locally; update assertions to use the local email and
keep Users.findOne({ email: testEmail }) references consistent with the chosen
approach.
In `@tests/unit/controllers/authController.test.ts`:
- Around line 45-57: The test for authController.register lacks an assertion
ensuring the next error handler wasn't invoked; update the test in
authController.test.ts to assert that the jest mock next was not called after
invoking authController.register (and apply the same pattern to other tests in
this file), i.e. after awaiting flushPromises verify next was not called (or
explicitly called with expected error in error-path tests) alongside the
existing assertions for registerMock, res.status and res.json to ensure error
propagation behavior is covered.
- Around line 1-28: Add a beforeEach block to clear/reset the module-level mocks
so tests don't leak state: call jest.clearAllMocks() and jest.resetAllMocks()
(and optionally jest.restoreAllMocks()) in a beforeEach placed in this test file
to reset registerMock, loginMock, verifyMock, logoutMock, refreshMock, meMock
and the AuthServiceMock between tests; this ensures each test starts with fresh
call histories and implementations for those mocks.
In `@tests/unit/controllers/loadController.test.ts`:
- Around line 24-49: Add error-path unit tests for loadController.startLoad by
mocking createTest (createTestMock) to reject with an Error and asserting that
startLoad calls next with that error and does not send a success response;
specifically, add a test that stubs createTestMock.mockRejectedValueOnce(new
Error("boom")), calls loadController.startLoad(req, res, next), awaits
flushPromises(), then expect(next).toHaveBeenCalledWith(expect.any(Error)) and
expect(res.status).not.toHaveBeenCalled() /
expect(res.json).not.toHaveBeenCalled(); also add a variant that verifies proper
handling of rejection payloads (e.g., an Error with a message) so error details
flow to next.
- Around line 37-38: The test currently calls loadController.startLoad(req, res,
next) and then uses flushPromises(); instead await the controller invocation
directly: call and await loadController.startLoad(req, res, next) (removing the
flushPromises() usage) so the test waits for the actual Promise returned by
startLoad (likely from asyncHandler) to resolve; update the test to remove or
replace the flushPromises() call and ensure assertions run after the awaited
startLoad completes.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (12)
src/controllers/auth.tssrc/middlewares/joiValidation.tssrc/models/load.tssrc/routes/auth.tssrc/services/emailService.tssrc/services/loadService.tssrc/types/index.tssrc/validations/load.tstests/auth.test.tstests/auth/auth.test.tstests/unit/controllers/authController.test.tstests/unit/controllers/loadController.test.ts
💤 Files with no reviewable changes (2)
- src/services/emailService.ts
- tests/auth.test.ts
🧰 Additional context used
🧬 Code graph analysis (4)
src/services/loadService.ts (1)
src/services/loadervice.ts (1)
loadService(3-8)
src/types/index.ts (1)
src/utils/index.ts (1)
createAPIResponse(14-19)
tests/auth/auth.test.ts (1)
src/utils/jwt.ts (1)
generateToken(8-29)
src/routes/auth.ts (1)
src/controllers/auth.ts (2)
logout(36-42)refresh(44-50)
🔇 Additional comments (7)
src/services/loadService.ts (1)
3-3: LGTM!The import path change from
../models/test.jsto../models/load.jsaligns with the broader refactor to consolidate load-related models.src/types/index.ts (1)
3-3: LGTM!Import path update aligns with the model consolidation.
src/controllers/auth.ts (1)
49-49: LGTM!Minor formatting fix for consistency.
tests/unit/controllers/authController.test.ts (2)
32-43: LGTM!The
createReshelper provides a well-structured chainable mock response, andflushPromisescorrectly flushes the microtask queue for async controller handlers.
59-137: LGTM!The remaining test cases (login, verify, refresh, me, logout) are well-structured and correctly verify the expected interactions with the mocked service, response status codes, cookies, and response methods.
tests/auth/auth.test.ts (2)
1-17: LGTM!The setup correctly mocks the email service before dynamically importing the application modules, ensuring the mock is in place when the modules are loaded. Using
jest.unstable_mockModulewith dynamic imports is the proper pattern for ESM mocking.
19-67: LGTM!The helper functions encapsulate the authentication workflow steps effectively. The verification token generation correctly uses the JWT configuration from the environment.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
| schema: Joi.Schema, | ||
| property: "body" | "query" | "params" = "body", | ||
| options: Joi.ValidationOptions = { abortEarly: false } | ||
| options: Joi.ValidationOptions = { abortEarly: false, stripUnknown: true }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for schemas using unknown(false)
rg -n 'unknown\s*\(\s*false\s*\)' --type tsRepository: deepx4344/SurgeTest
Length of output: 108
🏁 Script executed:
#!/bin/bash
# Check the joiValidation.ts file
echo "=== joiValidation.ts ==="
cat -n src/middlewares/joiValidation.ts | head -50
echo -e "\n=== load.ts schema context ==="
cat -n src/validations/load.tsRepository: deepx4344/SurgeTest
Length of output: 1797
🌐 Web query:
Joi stripUnknown precedence over unknown(false) validation order
💡 Result:
In Joi, stripUnknown effectively wins over unknown(false) (the default) for object keys:
- If you validate an object with extra keys using
unknown(false), Joi would normally raiseobject.unknown(“is not allowed”). But if you also setstripUnknown(e.g.{ stripUnknown: true }or{ stripUnknown: { objects: true } }), Joi will remove the unknown keys and not error. This is shown in the Joi repo issue repro: the same schema that errors withoutstripUnknownreturns{ error: null, value: <stripped> }withstripUnknownenabled. [1] object.unknown([allow])controls whether unknown keys are allowed/ignored at the schema level. [2]stripUnknownis a validation preference that deletes unknown keys from the validated value. [3][4]- Also,
stripUnknownremoval happens even if the schema allows unknown keys viaobject().unknown()—it still strips them whenstripUnknownis on (the “unexpected interaction” noted in the same issue). [1]
So, validation “order/precedence” for this behavior is: when stripUnknown is enabled, unknown keys are stripped instead of producing an object.unknown error, regardless of unknown(false) (and historically even regardless of unknown(true)/.unknown()). [1]
Practical takeaway
- Want an error on extra keys? Don’t use
stripUnknown; keepunknown(false)(default). - Want to silently drop extra keys? Use
stripUnknown(you can keepunknown(false); it won’t error). [1][3]
Sources: [1] [2] [3] [4]
🏁 Script executed:
#!/bin/bash
# Search for usage of validateSchema with loadSchema
echo "=== Looking for validateSchema usage ==="
rg -n 'validateSchema' --type ts -A 3 -B 1
echo -e "\n=== Looking for loadSchema usage ==="
rg -n 'loadSchema' --type ts -A 2 -B 1Repository: deepx4344/SurgeTest
Length of output: 2422
stripUnknown: true default makes unknown(false) schemas ineffective.
At line 9 of src/routes/load.ts, validateSchema(loadSchema) is called without custom options, using the middleware's default stripUnknown: true. Since loadSchema explicitly sets .unknown(false) to reject unknown keys, but the middleware strips unknown keys before schema validation, the schema's validation rule never gets triggered. Unknown properties are silently removed instead of returning a validation error.
If schemas like loadSchema are intentionally strict about rejecting unknown fields, either:
- Remove
stripUnknown: truefrom the middleware defaults, or - Pass custom options
{ stripUnknown: false }when callingvalidateSchema(loadSchema)(and other strict schemas)
🤖 Prompt for AI Agents
In `@src/middlewares/joiValidation.ts` at line 10, The middleware default options
set stripUnknown: true which removes unknown properties before Joi runs, so
schemas that use .unknown(false) (e.g. loadSchema used via
validateSchema(loadSchema) in src/routes/load.ts) never get an "unknown field"
error; fix by either removing stripUnknown: true from the default
Joi.ValidationOptions in the middleware (options variable in joiValidation.ts)
or make validateSchema accept/forward custom options and update the call site
validateSchema(loadSchema) to pass { stripUnknown: false } for strict schemas
like loadSchema so Joi's .unknown(false) can reject extra keys.
| router.get("/verify/:token", verify); | ||
| router.post("/logout",authMiddleware, logout); | ||
| router.post("/logout", authMiddleware, logout); | ||
| router.post("/refresh", refresh); |
There was a problem hiding this comment.
Missing rate limiting and no guard against missing cookies.
The /refresh endpoint lacks the authlimiter middleware that protects /login and /register. This could allow attackers to abuse the refresh mechanism.
Additionally, the refresh controller (in src/controllers/auth.ts, lines 44-49) accesses req.signedCookies["tokens"].refreshToken without checking if tokens exists. If the cookie is missing, this will throw a TypeError.
Consider:
- Adding
authlimiterto prevent abuse - Adding validation for cookie presence (either via middleware or in the controller)
Suggested fix
-router.post("/refresh", refresh);
+router.post("/refresh", authlimiter, refresh);And in the controller, add a guard:
const tokens: Tokens | undefined = req.signedCookies["tokens"];
if (!tokens?.refreshToken) {
return res.status(401).json(createAPIResponse({
success: false,
message: "No refresh token provided",
}));
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| router.post("/refresh", refresh); | |
| router.post("/refresh", authlimiter, refresh); |
🤖 Prompt for AI Agents
In `@src/routes/auth.ts` at line 21, The /refresh route currently lacks the
authlimiter middleware and the refresh controller (function refresh in
src/controllers/auth.ts) dereferences req.signedCookies["tokens"].refreshToken
without checking for tokens, which can throw a TypeError and allows brute
forcing; update the router.post("/refresh", refresh) registration to include the
existing authlimiter middleware (same as used for /login and /register) and add
a guard at the start of the refresh controller to validate presence of
req.signedCookies["tokens"] and tokens.refreshToken, returning a 401 JSON API
response (using createAPIResponse) if missing; ensure the change references the
refresh handler and authlimiter symbol so the middleware and null-check are
applied consistently.
| export interface ApiResponseinput<T = unknown> { | ||
| success: boolean; | ||
| message: string; | ||
| token?: string; | ||
| tokens?: Tokens; | ||
| user?: User; | ||
| data?: string; | ||
| datas?: string[] | ||
| data?: T; | ||
| datas?: T[]; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Good improvement: Generic interface enhances type safety.
The generic ApiResponseinput<T> allows for typed data and datas fields. However, for consumers to fully benefit, createAPIResponse in src/utils/index.ts (line 13-18) should also be made generic:
function createAPIResponse<T>(input: ApiResponseinput<T>) {
return {
...input,
timestamp: new Date().toISOString(),
};
}Without this, the generic parameter won't propagate through the helper function.
🤖 Prompt for AI Agents
In `@src/types/index.ts` around lines 23 - 30, The ApiResponseinput<T> generic
isn’t propagated because createAPIResponse is not generic; update the
createAPIResponse function to accept a generic type parameter (e.g., function
createAPIResponse<T>(input: ApiResponseinput<T>)) and have it return the
appropriately typed response including the added timestamp so callers receive
the correct generic typing for data/datas; reference the ApiResponseinput and
createAPIResponse symbols when making this change.
| concurrency: Joi.number().min(1).default(10), | ||
| duration: Joi.number().min(1).default(30), | ||
| }).unknown(true); | ||
| }).unknown(false); |
There was a problem hiding this comment.
This unknown(false) is effectively a no-op due to middleware defaults.
The intent to reject unknown fields is good for strict validation. However, since joiValidation.ts now defaults to stripUnknown: true, unknown properties are stripped before this check runs, meaning this constraint will never trigger a validation error.
To enforce strict rejection of unknown fields, either:
- Remove
stripUnknownfrom the middleware defaults, or - Pass
{ stripUnknown: false }when callingvalidateSchema(loadSchema)in the route
🤖 Prompt for AI Agents
In `@src/validations/load.ts` at line 15, The unknown(false) check in loadSchema
is ineffective because the middleware in joiValidation.ts currently strips
unknown properties by default; update the call site that applies
validateSchema(loadSchema) to pass an override option { stripUnknown: false }
(or alternatively remove/disable stripUnknown in joiValidation.ts) so that
unknown(false) can actually reject unknown fields; reference the loadSchema
defined in src/validations/load.ts and the validateSchema(...) usage in your
route/middleware to apply the fix.
| beforeAll(async () => { | ||
| await connectDB(); | ||
| if (mongoose.connection.db) { | ||
| await mongoose.connection.db | ||
| .collection("users") | ||
| .deleteMany({ email: testEmail }); | ||
| } | ||
| },20000); | ||
|
|
||
| afterAll(async () => { | ||
| if (mongoose.connection.db) { | ||
| await mongoose.connection.db | ||
| .collection("users") | ||
| .deleteMany({ email: testEmail }); | ||
| } | ||
| await mongoose.disconnect(); | ||
| },20000); |
There was a problem hiding this comment.
Minor formatting: Add space after comma in timeout parameter.
🔧 Proposed fix
-},20000);
+}, 20000);Apply to both beforeAll (line 76) and afterAll (line 85).
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| beforeAll(async () => { | |
| await connectDB(); | |
| if (mongoose.connection.db) { | |
| await mongoose.connection.db | |
| .collection("users") | |
| .deleteMany({ email: testEmail }); | |
| } | |
| },20000); | |
| afterAll(async () => { | |
| if (mongoose.connection.db) { | |
| await mongoose.connection.db | |
| .collection("users") | |
| .deleteMany({ email: testEmail }); | |
| } | |
| await mongoose.disconnect(); | |
| },20000); | |
| beforeAll(async () => { | |
| await connectDB(); | |
| if (mongoose.connection.db) { | |
| await mongoose.connection.db | |
| .collection("users") | |
| .deleteMany({ email: testEmail }); | |
| } | |
| }, 20000); | |
| afterAll(async () => { | |
| if (mongoose.connection.db) { | |
| await mongoose.connection.db | |
| .collection("users") | |
| .deleteMany({ email: testEmail }); | |
| } | |
| await mongoose.disconnect(); | |
| }, 20000); |
🤖 Prompt for AI Agents
In `@tests/auth/auth.test.ts` around lines 69 - 85, Fix the minor formatting in
the test hooks by adding a space after the comma in the timeout parameter for
both beforeAll and afterAll; locate the beforeAll(...) and afterAll(...)
invocations (which call connectDB(), use mongoose.connection.db to deleteMany on
the "users" collection with testEmail, and call mongoose.disconnect()) and
change the timeout argument formatting from "},20000);" to "}, 20000);" in both
places.
| describe("Auth routes", () => { | ||
| it("registers a new user", async () => { | ||
| const registerResponse = await registerUser(); | ||
| expect(registerResponse.body).toMatchObject({ | ||
| success: true, | ||
| message: "User Created Successfully", | ||
| }); | ||
|
|
||
| const user = await Users.findOne({ email: testEmail }).lean(); | ||
| expect(user).toBeTruthy(); | ||
| expect(user?.verified).toBe(false); | ||
| }); | ||
|
|
||
| it("verifies a registered user", async () => { | ||
| await verifyUser(); | ||
|
|
||
| const verifiedUser = await Users.findOne({ email: testEmail }).lean(); | ||
| expect(verifiedUser?.verified).toBe(true); | ||
| }); | ||
|
|
||
| it("logs in a verified user", async () => { | ||
| const loginResponse = await loginUser(); | ||
| expect(loginResponse.body).toMatchObject({ | ||
| success: true, | ||
| message: "User Logged In Successfully", | ||
| }); | ||
| expect(loginResponse.headers["set-cookie"]).toBeDefined(); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Tests are sequentially dependent, which may cause cascading failures.
The tests rely on shared state: "verifies a registered user" assumes "registers a new user" ran first, and "logs in a verified user" assumes verification completed. If any earlier test fails or is skipped, subsequent tests will fail with misleading errors.
Consider moving the prerequisite steps into the test setup or using explicit dependencies.
♻️ Proposed refactor: Move shared setup into beforeAll or make tests independent
Option 1: Move registration to beforeAll for dependent tests
+let isRegistered = false;
+let isVerified = false;
+
describe("Auth routes", () => {
+ beforeAll(async () => {
+ await registerUser();
+ isRegistered = true;
+ await verifyUser();
+ isVerified = true;
+ });
+
it("registers a new user", async () => {
- const registerResponse = await registerUser();
- expect(registerResponse.body).toMatchObject({
+ // Registration already done in beforeAll, verify the state
+ const user = await Users.findOne({ email: testEmail }).lean();
+ expect(user).toBeTruthy();
+ });Option 2: Make each test fully independent (preferred for isolation)
Each test registers its own user with a unique email, ensuring complete isolation.
🤖 Prompt for AI Agents
In `@tests/auth/auth.test.ts` around lines 87 - 115, The tests are dependent on
shared state; make them independent by either (A) moving the shared setup into a
beforeAll that calls registerUser() (and verifyUser() if needed) and then
querying Users.findOne({ email: testEmail }) in tests, or (B, preferred) have
each it() create its own user by calling registerUser() with a unique email and,
when needed, calling verifyUser() or loginUser() within the same test so
registerUser, verifyUser, and loginUser are invoked locally; update assertions
to use the local email and keep Users.findOne({ email: testEmail }) references
consistent with the chosen approach.
| import { jest, describe, it, expect } from "@jest/globals"; | ||
|
|
||
| const registerMock = jest.fn<any>().mockResolvedValue(undefined); | ||
| const loginMock = jest.fn<any>().mockResolvedValue({ | ||
| accessToken: "access-token", | ||
| refreshToken: "refresh-token", | ||
| }); | ||
| const verifyMock = jest.fn<any>().mockResolvedValue(undefined); | ||
| const logoutMock = jest.fn<any>().mockResolvedValue(undefined); | ||
| const refreshMock = jest.fn<any>().mockResolvedValue("new-access-token"); | ||
| const meMock = jest.fn<any>().mockResolvedValue({ | ||
| id: "user-id", | ||
| email: "user@example.com", | ||
| paid: false, | ||
| }); | ||
|
|
||
| const AuthServiceMock = jest.fn().mockImplementation(() => ({ | ||
| register: registerMock, | ||
| login: loginMock, | ||
| verify: verifyMock, | ||
| logout: logoutMock, | ||
| refresh: refreshMock, | ||
| me: meMock, | ||
| })); | ||
|
|
||
| jest.unstable_mockModule("../../../src/services/authService.js", () => ({ | ||
| default: AuthServiceMock, | ||
| })); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Mocks are not reset between tests, risking test pollution.
The mock functions are defined at module scope and not cleared between tests. If one test modifies mock behavior or accumulates call history, subsequent tests may produce false positives or negatives.
♻️ Proposed fix: Add beforeEach to reset mocks
const authController = await import("../../../src/controllers/auth.js");
+import { beforeEach } from "@jest/globals";
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
const createRes = () => {🤖 Prompt for AI Agents
In `@tests/unit/controllers/authController.test.ts` around lines 1 - 28, Add a
beforeEach block to clear/reset the module-level mocks so tests don't leak
state: call jest.clearAllMocks() and jest.resetAllMocks() (and optionally
jest.restoreAllMocks()) in a beforeEach placed in this test file to reset
registerMock, loginMock, verifyMock, logoutMock, refreshMock, meMock and the
AuthServiceMock between tests; this ensures each test starts with fresh call
histories and implementations for those mocks.
| describe("Auth controller", () => { | ||
| it("registers a user", async () => { | ||
| const req: any = { body: { email: "user@example.com", password: "Pass.!1" } }; | ||
| const res = createRes(); | ||
| const next = jest.fn(); | ||
|
|
||
| authController.register(req, res, next); | ||
| await flushPromises(); | ||
|
|
||
| expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1"); | ||
| expect(res.status).toHaveBeenCalledWith(201); | ||
| expect(res.json).toHaveBeenCalled(); | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Missing assertion on next function for error propagation.
The next function is created but never verified. If the controller inadvertently calls next(error), the test would still pass. Consider asserting that next was not called (or called with specific errors for error-path tests).
♻️ Proposed fix: Add assertion for next
expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1");
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalled();
+ expect(next).not.toHaveBeenCalled();
});Apply the same pattern to all other test cases.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| describe("Auth controller", () => { | |
| it("registers a user", async () => { | |
| const req: any = { body: { email: "user@example.com", password: "Pass.!1" } }; | |
| const res = createRes(); | |
| const next = jest.fn(); | |
| authController.register(req, res, next); | |
| await flushPromises(); | |
| expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1"); | |
| expect(res.status).toHaveBeenCalledWith(201); | |
| expect(res.json).toHaveBeenCalled(); | |
| }); | |
| describe("Auth controller", () => { | |
| it("registers a user", async () => { | |
| const req: any = { body: { email: "user@example.com", password: "Pass.!1" } }; | |
| const res = createRes(); | |
| const next = jest.fn(); | |
| authController.register(req, res, next); | |
| await flushPromises(); | |
| expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1"); | |
| expect(res.status).toHaveBeenCalledWith(201); | |
| expect(res.json).toHaveBeenCalled(); | |
| expect(next).not.toHaveBeenCalled(); | |
| }); |
🤖 Prompt for AI Agents
In `@tests/unit/controllers/authController.test.ts` around lines 45 - 57, The test
for authController.register lacks an assertion ensuring the next error handler
wasn't invoked; update the test in authController.test.ts to assert that the
jest mock next was not called after invoking authController.register (and apply
the same pattern to other tests in this file), i.e. after awaiting flushPromises
verify next was not called (or explicitly called with expected error in
error-path tests) alongside the existing assertions for registerMock, res.status
and res.json to ensure error propagation behavior is covered.
| describe("Load controller", () => { | ||
| it("starts a load test", async () => { | ||
| const req: any = { | ||
| body: { | ||
| url: "https://example.com", | ||
| method: "GET", | ||
| concurrency: 5, | ||
| duration: 10, | ||
| }, | ||
| }; | ||
| const res = createRes(); | ||
| const next = jest.fn(); | ||
|
|
||
| loadController.startLoad(req, res, next); | ||
| await flushPromises(); | ||
|
|
||
| expect(createTestMock).toHaveBeenCalledWith(req.body); | ||
| expect(res.status).toHaveBeenCalledWith(202); | ||
| expect(res.json).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| success: true, | ||
| message: "Task created successfully", | ||
| data: "test-id", | ||
| }), | ||
| ); | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Test coverage is limited to the happy path.
Consider adding tests for error scenarios:
- What happens when
createTestrejects? - Does the
nextfunction get called with the error?
Would you like me to generate additional test cases for error handling?
🤖 Prompt for AI Agents
In `@tests/unit/controllers/loadController.test.ts` around lines 24 - 49, Add
error-path unit tests for loadController.startLoad by mocking createTest
(createTestMock) to reject with an Error and asserting that startLoad calls next
with that error and does not send a success response; specifically, add a test
that stubs createTestMock.mockRejectedValueOnce(new Error("boom")), calls
loadController.startLoad(req, res, next), awaits flushPromises(), then
expect(next).toHaveBeenCalledWith(expect.any(Error)) and
expect(res.status).not.toHaveBeenCalled() /
expect(res.json).not.toHaveBeenCalled(); also add a variant that verifies proper
handling of rejection payloads (e.g., an Error with a message) so error details
flow to next.
| loadController.startLoad(req, res, next); | ||
| await flushPromises(); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider awaiting the controller call directly.
The flushPromises() pattern works but can be fragile. If startLoad returns a Promise (which it likely does via asyncHandler), awaiting it directly is more robust:
- loadController.startLoad(req, res, next);
- await flushPromises();
+ await loadController.startLoad(req, res, next);This ensures the test waits for the actual promise to resolve rather than relying on microtask timing.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| loadController.startLoad(req, res, next); | |
| await flushPromises(); | |
| await loadController.startLoad(req, res, next); |
🤖 Prompt for AI Agents
In `@tests/unit/controllers/loadController.test.ts` around lines 37 - 38, The test
currently calls loadController.startLoad(req, res, next) and then uses
flushPromises(); instead await the controller invocation directly: call and
await loadController.startLoad(req, res, next) (removing the flushPromises()
usage) so the test waits for the actual Promise returned by startLoad (likely
from asyncHandler) to resolve; update the test to remove or replace the
flushPromises() call and ensure assertions run after the awaited startLoad
completes.
No description provided.